# -*- coding: utf-8 -*-
"""
Created on Wed May 15 17:48:57 2019

@author: yaoyu
"""

import requests
import re
import json
import pandas as pd
from datetime import date
 
def retrieve_quotes_historical(stock_code):
    quotes = []
    url = 'https://finance.yahoo.com/quote/%s/history?p=%s' % (stock_code, stock_code)
    try:
        r = requests.get(url)
    except ConnectionError as err:
        print(err)
    m = re.findall('"HistoricalPriceStore":{"prices":(.*?),"isPending"', r.text)
    if m:
        quotes = json.loads(m[0])       # m = ['[{...},{...},...]'] 
        quotes = quotes[::-1]         # 原先数据为date最新的在最前面
    return  [item for item in quotes if not 'type' in item]
 
quotes = retrieve_quotes_historical('INTC')
attributes = ['close','date','high','low','open','volume']
quotesdf = pd.DataFrame(quotes, columns=attributes)
# quotesdf = quotesdf_ori.drop(['adjclose'], axis = 1)  可用本语句删除adjclose列
print(quotesdf)




list1 = []
#quotes=quotesdf
for i in range(len(quotes)):
    x = date.fromtimestamp(quotes[i][ 'date'])
    y = date.strftime(x, '%Y/%m/%d')
    list1.append(y)
quotesdf_ori = pd.DataFrame(quotes, index = list1)
quotesdf = quotesdf_ori.drop(['date'], axis =1)
print(quotesdf)


list1 = []
tmpdf = quotesdf['2018/07/01':'2018/12/31']
for i in range(len(tmpdf)):
    list1.append(int(tmpdf.index[i][5:7]))
    
tmpdf['____'] = list1
print(tmpdf[tmpdf.close > _____]['month'].value_counts())